package com.example.springdemotest;

import com.example.springdemotest.bean.Photo;
import com.example.springdemotest.mapper.PhotoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@RestController
@ResponseBody
public class FillUpdataController {
    private static final String UPLOADED_FOLDER=System.getProperty("user.dir")+"/myData/";

    @Autowired
    private PhotoMapper photoMapper;

    @PostMapping("/upload")
    public String up(int id,MultipartFile photo) throws IOException {
        saveFile(id,photo);
        return "Successfully！";
    }

    public void saveFile(int id,MultipartFile photo) throws IOException {
        File dir=new File(UPLOADED_FOLDER);
        if(!dir.exists()){
            dir.mkdir();
        }
        File file=new File(UPLOADED_FOLDER+photo.getOriginalFilename());
        photo.transferTo(file);
        Date upload_data=new Date();
        photoMapper.insert_photo(id,photo.getOriginalFilename(),UPLOADED_FOLDER,upload_data);
    }

    @GetMapping("/select")
    public String select(int id){
        Photo photo=photoMapper.select(id);
        System.out.println(photo);
        return "The name is : "+photo.getName()+" |**| The upload_date is : "+photo.getUploadDate();
    }

}
